﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;

namespace TK
{
    public partial class CustomSerializer
    {
        void writeGeneric(CustomSerializerState state, object o)
        {
            // fix for fast type find
            var type = o.GetType();
            var gga = type.GetGenericArguments();
            var arg0 = gga[0];
            if (o is IList) writeGenericList(state, o as IList, arg0);
            else if (o is IDictionary) writeGenericDictionary(state, o as IDictionary, arg0, gga[1]);
            else if (type == typeof (HashSet<>).MakeGenericType(arg0) || // todo optimize
                     type == typeof (Queue<>).MakeGenericType(arg0) ||
                     type == typeof (SortedSet<>).MakeGenericType(arg0) ||
                     type == typeof(Stack<>).MakeGenericType(arg0)) writeIEnumerable(state, o as IEnumerable, arg0);
            else if (type.Name.StartsWith("Tuple`")) writeGenericTuple(state, o);
            else Trace.WriteLine("Unsupported type: " + type.AssemblyQualifiedName + ", skipped");
        }

        object readGeneric(CustomSerializerState state, Type type, Type ownerType, string propertyName)
        {
            if (type.GetInterface("IList") != null) return readGenericList(state, type, ownerType, propertyName);
            if (type.GetInterface("IDictionary") != null) return readGenericDictionary(state, type, ownerType, propertyName);

            var gga = type.GetGenericArguments();
            var arg0 = gga[0];
            if (type == typeof(HashSet<>).MakeGenericType(arg0) || // todo optimize
                type == typeof (Queue<>).MakeGenericType(arg0) ||
                type == typeof (SortedSet<>).MakeGenericType(arg0) ||
                type == typeof (Stack<>).MakeGenericType(arg0)) return readIEnumerable(state, type, ownerType, propertyName);

            if (type.Name.StartsWith("Tuple`")) return readGenericTuple(state, type);

            return null;
        }
    }
}